//
//  PPAlbumActivityTimelineViewController.m
//  pickpic
//
//  Created by Jinxiao on 10/5/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPAlbumActivityTimelineViewController.h"
#import "PPTimelineDetailViewController.h"
#import "PPProfileViewController.h"
#import "PPTimelinePictureViewController.h"
#import "PPCommentTimelineViewController.h"

#import "PPAlbumActivityTimelineTableViewCommentCell.h"
#import "PPAlbumActivityTimelineTableViewSectionHeaderView.h"

#import "PPTimelineAlbumActivityObject.h"
#import "PPNetworkService.h"

static NSInteger kCount = 20;

@interface PPAlbumActivityTimelineViewController () <PPCommentTimelineViewControllerDelegate, PPAlbumActivityTimelineTableViewSectionHeaderViewDelegate>
@end

@implementation PPAlbumActivityTimelineViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"朋友";
    self.view.backgroundColor = [UIColor colorWithRGBHex:0xf2f2f2];

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, CGFLOAT_MIN)];
    self.tableView.tableHeaderView = headerView;

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.tableView registerClass:[PPAlbumActivityTimelineTableViewCommentCell class] forCellReuseIdentifier:@"commentCell"];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.items.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    PPTimelineAlbumActivityObject *activity = [self.items safeObjectAtIndex:section];

    return MIN(activity.album.comments.count, 3);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    PPTimelineAlbumActivityObject *activity = [self.items safeObjectAtIndex:indexPath.section];
    PPAlbumObject *album = activity.album;
    PPTimelineCommentObject *comment = [album.comments safeObjectAtIndex:indexPath.row];

    return [PPAlbumActivityTimelineTableViewCommentCell heightForComment:comment constrainedSize:CGSizeMake(tableView.width, 1000)];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    PPTimelineAlbumActivityObject *activity = [self.items safeObjectAtIndex:section];

    return [PPAlbumActivityTimelineTableViewSectionHeaderView heightForActivity:activity];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    PPTimelineAlbumActivityObject *activity = [self.items safeObjectAtIndex:section];
    PPAlbumObject *album = activity.album;

    if(album.commentCount > 3) {
        return 45;
    } else if(album.commentCount == 0) {
        return 15;
    } else {
        return 22;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PPAlbumActivityTimelineTableViewCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell"];

    PPTimelineAlbumActivityObject *activity = [self.items safeObjectAtIndex:indexPath.section];
    PPAlbumObject *album = activity.album;

    PPTimelineCommentObject *comment = [album.comments safeObjectAtIndex:indexPath.row];
    cell.comment = comment;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [MobClick event:@"99"];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    PPTimelineAlbumActivityObject *activity = [self.items safeObjectAtIndex:indexPath.section];

    PPAlbumObject *album = activity.album;

    PPTimelineCommentObject *comment = [album.comments safeObjectAtIndex:indexPath.row];

    PPCommentTimelineViewController *commentViewController = [[PPCommentTimelineViewController alloc] init];
    commentViewController.albumID = album.albumID.integerValue;
    commentViewController.ownerID = album.userID;
    commentViewController.comment = comment;
    commentViewController.delegate = self;
    commentViewController.userInfo = @(indexPath.section);
    commentViewController.version = activity.version;
    [self.navigationController pushViewController:commentViewController animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    PPTimelineAlbumActivityObject *activity = [self.items safeObjectAtIndex:section];

    PPAlbumActivityTimelineTableViewSectionHeaderView *headerView = [[NSBundle mainBundle] loadNibNamed:@"PPAlbumActivityTimelineTableViewSectionHeaderView" owner:nil options:nil].firstObject;
    headerView.clipsToBounds = YES;
    headerView.backgroundColor = [UIColor clearColor];
    headerView.frame = CGRectMake(0, 0, tableView.width, [self tableView:tableView heightForHeaderInSection:section]);
    headerView.delegate = self;
    headerView.activity = activity;
    headerView.delegateViewController = self;

    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor clearColor];
    headerView.frame = CGRectMake(0, 0, tableView.width, [self tableView:tableView heightForFooterInSection:section]);

    UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, headerView.width, headerView.height - 10);
    view.backgroundColor = [UIColor whiteColor];
    [view addBottomBorderWithColor:kLineColor andWidth:kLineWidth];

    PPTimelineAlbumActivityObject *activity = [self.items safeObjectAtIndex:section];
    PPAlbumObject *album = activity.album;

    if(album.commentCount > 3) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitle:[NSString stringWithFormat:@"全部%li条评论", album.commentCount] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRGBHex:0x999999] forState:UIControlStateNormal];
        button.contentEdgeInsets = UIEdgeInsetsMake(4, 15, 4, 15);
        [button sizeToFit];
        button.frame = CGRectMake(0, 0, button.width, button.height);
        [view addSubview:button];

        __weak typeof(self)weakSelf = self;
        [button setActionBlock:^(UIControl *control) {
            PPCommentTimelineViewController *commentViewController = [[PPCommentTimelineViewController alloc] init];
            commentViewController.albumID = album.albumID.integerValue;
            commentViewController.ownerID = album.userID;
            commentViewController.delegate = weakSelf;
            commentViewController.userInfo = @(section);
            commentViewController.version = activity.version;
            [weakSelf.navigationController pushViewController:commentViewController animated:YES];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    [headerView addSubview:view];

    return headerView;
}

#pragma mark - Timeline

- (NSArray *)initialItems {
    NSString *cacheFilePath = [self cacheFilePath];

    NSData *data = [NSData dataWithContentsOfFile:cacheFilePath];

    if(data != nil) {
        NSArray *items = [NSKeyedUnarchiver unarchiveObjectWithData:data];

        for(PPTimelineAlbumActivityObject *activity in items) {

            DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:activity.brief];
            editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
            editor.defaultFont = [UIFont systemFontOfSize:15];

            DGCoreTextPatternSetting *nameSetting = [[DGCoreTextPatternSetting alloc] init];
            nameSetting.predicate = activity.album.title;
            nameSetting.defaultFont = [UIFont systemFontOfSize:15];
            nameSetting.highlightedFont = [UIFont systemFontOfSize:15];
            nameSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
            nameSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

            __weak typeof(self)weakSelf = self;
            nameSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                [weakSelf didPressedActivity:activity];
            };
            [editor preprocessWithPatternSetting:nameSetting];
            [editor process];

            activity.editor = editor;


            [activity.album.comments enumerateObjectsUsingBlock:^(PPTimelineCommentObject *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
                NSString *content = nil;

                if(obj.receiver == nil) {
                    content = [NSString stringWithFormat:@"\u200B%@: %@", obj.sender.name, obj.content];;
                } else {
                    content = [NSString stringWithFormat:@"\u200B%@ 回复 \u200C%@: %@", obj.sender.name, obj.receiver.name, obj.content];
                }

                DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:content];
                editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
                editor.defaultFont = [UIFont systemFontOfSize:15];

                {
                    DGCoreTextPatternSetting *senderSetting = [[DGCoreTextPatternSetting alloc] init];
                    senderSetting.predicate = @"\u200B[\\u4e00-\\u9fa5\\w\\-]+";
                    senderSetting.defaultFont = [UIFont systemFontOfSize:15];
                    senderSetting.highlightedFont = [UIFont systemFontOfSize:15];
                    senderSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
                    senderSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

                    __weak typeof(self)weakSelf = self;
                    senderSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                        [weakSelf didPressedCommentSender:obj];
                    };
                    [editor preprocessWithPatternSetting:senderSetting];
                }

                {
                    DGCoreTextPatternSetting *receiverSetting = [[DGCoreTextPatternSetting alloc] init];
                    receiverSetting.predicate = @"\u200C[\\u4e00-\\u9fa5\\w\\-]+";
                    receiverSetting.defaultFont = [UIFont systemFontOfSize:15];
                    receiverSetting.highlightedFont = [UIFont systemFontOfSize:15];
                    receiverSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
                    receiverSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

                    __weak typeof(self)weakSelf = self;
                    receiverSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                        [weakSelf didPressedCommentReceiver:obj];
                    };
                    [editor preprocessWithPatternSetting:receiverSetting];
                }

                [editor process];

                obj.editor = editor;
            }];
        }

        return items;
    } else {
        return nil;
    }
}

- (void)cacheItems:(NSArray *)items {
    NSString *cacheFilePath = [self cacheFilePath];

    [NSKeyedArchiver archiveRootObject:items toFile:cacheFilePath];
}

- (void)fetchNewItems {
    [super fetchNewItems];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchMyMessageListWithType:[self preferredCategory] before:nil size:kCount onlyUnread:NO callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [weakSelf didReceiveNewResult:data ? : error];
    }];
}

- (void)fetchMoreItems {
    [super fetchMoreItems];

    PPTimelineAlbumActivityObject *activity = self.items.lastObject;

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchMyMessageListWithType:[self preferredCategory] before:@(activity.date.timeIntervalSince1970*1000) size:kCount onlyUnread:NO callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [self didReceiveMoreResult:error ? : data];
    }];
}

- (NSArray *)didReceiveNewResult:(id)result {
    NSArray *items = [super didReceiveNewResult:result];

    if([items count] >= kCount) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}

- (NSArray *)didReceiveMoreResult:(id)result {
    NSArray *items = [super didReceiveMoreResult:result];

    if([items count] >= kCount) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}

- (NSArray *)itemsFromResult:(id)result {
    NSMutableArray *items = [NSMutableArray array];

    for(NSDictionary *parameters in result) {
        PPTimelineAlbumActivityObject *activity = [PPTimelineAlbumActivityObject activityForParameters:parameters];

        if(activity != nil) {
            DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:activity.brief];
            editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
            editor.defaultFont = [UIFont systemFontOfSize:15];

            DGCoreTextPatternSetting *nameSetting = [[DGCoreTextPatternSetting alloc] init];
            nameSetting.predicate = activity.album.title;
            nameSetting.defaultFont = [UIFont systemFontOfSize:15];
            nameSetting.highlightedFont = [UIFont systemFontOfSize:15];
            nameSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
            nameSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

            __weak typeof(self)weakSelf = self;
            nameSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                [weakSelf didPressedActivity:activity];
            };
            [editor preprocessWithPatternSetting:nameSetting];
            [editor process];

            activity.editor = editor;

            [items addSafeObject:activity];
        }

        [activity.album.comments enumerateObjectsUsingBlock:^(PPTimelineCommentObject *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
            NSString *content = nil;

            if(obj.receiver == nil) {
                content = [NSString stringWithFormat:@"\u200B%@: %@", obj.sender.name, obj.content];;
            } else {
                content = [NSString stringWithFormat:@"\u200B%@ 回复 \u200C%@: %@", obj.sender.name, obj.receiver.name, obj.content];
            }

            DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:content];
            editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
            editor.defaultFont = [UIFont systemFontOfSize:15];

            {
                DGCoreTextPatternSetting *senderSetting = [[DGCoreTextPatternSetting alloc] init];
                senderSetting.predicate = @"\u200B[\\u4e00-\\u9fa5\\w\\-]+";
                senderSetting.defaultFont = [UIFont systemFontOfSize:15];
                senderSetting.highlightedFont = [UIFont systemFontOfSize:15];
                senderSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
                senderSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

                __weak typeof(self)weakSelf = self;
                senderSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                    [weakSelf didPressedCommentSender:obj];
                };
                [editor preprocessWithPatternSetting:senderSetting];
            }

            {
                DGCoreTextPatternSetting *receiverSetting = [[DGCoreTextPatternSetting alloc] init];
                receiverSetting.predicate = @"\u200C[\\u4e00-\\u9fa5\\w\\-]+";
                receiverSetting.defaultFont = [UIFont systemFontOfSize:15];
                receiverSetting.highlightedFont = [UIFont systemFontOfSize:15];
                receiverSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
                receiverSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

                __weak typeof(self)weakSelf = self;
                receiverSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                    [weakSelf didPressedCommentReceiver:obj];
                };
                [editor preprocessWithPatternSetting:receiverSetting];
            }

            [editor process];

            obj.editor = editor;
        }];
    }

    return items;
}

- (UITableViewStyle)preferredTableViewStyle {
    return UITableViewStyleGrouped;
}

- (void)didPressedActivity:(PPTimelineAlbumActivityObject *)activity {
    [MobClick event:@"98"];

    __weak typeof(self)weakSelf = self;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [PPNetworkService getAlbumDetailsByAlbumID:activity.album.albumID callback:^(id data, NSError *error) {
        [hud hide:YES];
        if(error == nil) {

            PPAlbumObject *album = [PPAlbumObject albumForParameters:data];
            PPTimelineDetailViewController *detailViewController = [[PPTimelineDetailViewController alloc] init];
            detailViewController.album = album;
            [weakSelf.navigationController pushViewController:detailViewController animated:YES];
        } else {

            [weakSelf.view toastMessage:[error networkPrompt] duration:1.0];
        }
    }];


}

- (void)didPressedCommentSender:(PPTimelineCommentObject *)comment {
    [MobClick event:@"100"];
    PPProfileViewController *profileViewController = [[PPProfileViewController alloc] init];
    profileViewController.userID = comment.sender.userID;
    [self.navigationController pushViewController:profileViewController animated:YES];
}

- (void)didPressedCommentReceiver:(PPTimelineCommentObject *)comment {
    PPProfileViewController *profileViewController = [[PPProfileViewController alloc] init];
    profileViewController.userID = comment.receiver.userID;
    [self.navigationController pushViewController:profileViewController animated:YES];
}


- (NSString *)preferredCategory {
    return nil;
}

- (NSString *)cacheFilePath {
    NSString *directory = [NSString stringWithFormat:@"%@_Activity_%@", DGCurrentAccount.userID, [self preferredCategory]];
    NSString *path = [[[NSFileManager defaultManager] documentDirectory] stringByAppendingPathComponent:directory];

    return path;
}

#pragma mark - PPCommentTimelineViewControllerDelegate

- (void)commentTimelineViewController:(PPCommentTimelineViewController *)commentTimelineViewController didInsertComment:(PPTimelineCommentObject *)comment {
    NSInteger section = [commentTimelineViewController.userInfo integerValue];

    PPTimelineAlbumActivityObject *activity = [self.items safeObjectAtIndex:section];
    PPAlbumObject *album = activity.album;

    NSMutableArray *comments = [NSMutableArray arrayWithArray:album.comments];

    if(comments.count == 3) {
        [comments removeLastObject];
    }

    NSString *content = nil;

    if(comment.receiver == nil) {
        content = [NSString stringWithFormat:@"\u200B%@: %@", comment.sender.name, comment.content];;
    } else {
        content = [NSString stringWithFormat:@"\u200B%@ 回复 \u200C%@: %@", comment.sender.name, comment.receiver.name, comment.content];
    }

    DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:content];
    editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
    editor.defaultFont = [UIFont systemFontOfSize:15];

    {
        DGCoreTextPatternSetting *senderSetting = [[DGCoreTextPatternSetting alloc] init];
        senderSetting.predicate = @"\u200B[\\u4e00-\\u9fa5\\w\\-]+";
        senderSetting.defaultFont = [UIFont systemFontOfSize:15];
        senderSetting.highlightedFont = [UIFont systemFontOfSize:15];
        senderSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
        senderSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

        __weak typeof(self)weakSelf = self;
        senderSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
            [weakSelf didPressedCommentSender:comment];
        };
        [editor preprocessWithPatternSetting:senderSetting];
    }

    {
        DGCoreTextPatternSetting *receiverSetting = [[DGCoreTextPatternSetting alloc] init];
        receiverSetting.predicate = @"\u200C[\\u4e00-\\u9fa5\\w\\-]+";
        receiverSetting.defaultFont = [UIFont systemFontOfSize:15];
        receiverSetting.highlightedFont = [UIFont systemFontOfSize:15];
        receiverSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
        receiverSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

        __weak typeof(self)weakSelf = self;
        receiverSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
            [weakSelf didPressedCommentReceiver:comment];
        };
        [editor preprocessWithPatternSetting:receiverSetting];
    }

    [editor process];

    comment.editor = editor;

    [comments insertObject:comment atIndex:0];

    album.comments = comments;

    album.commentCount++;

    [self.tableView reloadData];
}

- (void)commentTimelineViewController:(PPCommentTimelineViewController *)commentTimelineViewController didRemoveComment:(PPTimelineCommentObject *)comment {
    NSInteger section = [commentTimelineViewController.userInfo integerValue];

    PPTimelineAlbumActivityObject *activity = [self.items safeObjectAtIndex:section];
    PPAlbumObject *album = activity.album;

    PPTimelineCommentObject *removedComment = nil;

    NSMutableArray *comments = [NSMutableArray arrayWithArray:album.comments];

    for(PPTimelineCommentObject *comment_ in comments) {
        if([comment.commentID isEqual:comment_.commentID]) {
            removedComment = comment_;
            break;
        }
    }

    album.commentCount--;

    if(removedComment != nil) {
        [comments removeObject:removedComment];
        
        album.comments = comments;
    }
    
    [self.tableView reloadData];
}

#pragma mark - PPAlbumActivityTimelineTableViewSectionHeaderViewDelegate

- (void)sectionHeaderView:(PPAlbumActivityTimelineTableViewSectionHeaderView *)sectionHeaderView didSelectCommentListForActivity:(PPTimelineAlbumActivityObject *)activity {
    NSInteger section = [self.items indexOfObject:activity];

    PPCommentTimelineViewController *commentViewController = [[PPCommentTimelineViewController alloc] init];
    commentViewController.albumID = activity.album.albumID.integerValue;
    commentViewController.ownerID = activity.user.userID;
    commentViewController.delegate = self;
    commentViewController.userInfo = @(section);
    commentViewController.version = activity.version;
    [self.navigationController pushViewController:commentViewController animated:YES];
}

@end
